import { defineStore } from 'pinia'
import Storage from '@/utils/Storage'
interface ShopInfoStore {
    id: string
    logo: string
    name: string
    newTips: string
    status: string
    mode: string
    userId: string
    shopId: string
    shopType?: string
}
let shopInfo = {
    shopInfo: {
        id: '',
        logo: '',
        name: '',
        newTips: '',
        status: '',
        token: '',
        userId: '',
        nickname: '',
        refresh_token: '',
        shopId: '',
        mode: '',
        shopType: ''
    }
}
const localStorage = new Storage()
export const useShopInfoStore = defineStore('shopStore', {
    state: () => shopInfo,
    actions: {
        SET_SHOP_INFO(payload: ShopInfoStore) {
            shopInfo.shopInfo = Object.assign(shopInfo.shopInfo, payload)
            localStorage.setItem('shopStore', shopInfo, 60 * 60 * 24)
        },
        SET_SHOP_TOKEN(payload: { access_token: string; refresh_token: string }) {
            shopInfo.shopInfo.token = payload.access_token
            shopInfo.shopInfo.refresh_token = payload.refresh_token
            localStorage.setItem('shopStore', shopInfo, 60 * 60 * 24 * 30)
            return payload.access_token
        }
    },
    getters: {
        getterShopInfo: (state) => {
            return getShopInfoFn(state)
        },
        token: (state) => state.shopInfo.token,
        refresh_token: (state) => state.shopInfo.refresh_token,
    },
})
function getShopInfoFn(state: any) {
    console.log('judgeNotEmpty(state.shopInfo)', judgeNotEmpty(state.shopInfo))
    if (judgeNotEmpty(state.shopInfo)) {
        const localStorage = new Storage()
        const shopInfo = localStorage.getItem('shopStore')
        state.shopInfo = shopInfo.shopInfo

        // return shopInfo
        if (judgeNotEmpty(shopInfo)) {
            return { id: '', token: '' }
        } else {
            state.shopInfo = shopInfo
            return shopInfo
        }
    } else {
        return state.shopInfo
    }
}
/**
 * @LastEditors: vikingShip
 * @description: 判断shopInfo是否为空
 * @param {*} obj
 */
function judgeNotEmpty(shopInfo: any) {
    if (JSON.stringify(shopInfo) === '{}' || JSON.stringify(shopInfo) === 'null') return true
    if (Object.keys(shopInfo).length === 0) return true
    if (!shopInfo.id) return true
    return false
}
